package com.dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.File;
import java.util.List;

public class Dom4JTest {
    @Test
    public void test1(){
        try {
            //创建SAXReader
            SAXReader saxReader = new SAXReader();
            //读取XML文件
            Document document = saxReader.read(new File("src/main/resources/books.xml"));
            //获取根元素
            Element rootElement = document.getRootElement();
            //遍历book元素
            List<Element> bookElements = rootElement.elements("book");
            //<book id="1">
            //        <title>Java Programming</title>
            //        <author>John Doe</author>
            //        <price>29.99</price>
            //    </book>
            for (Element bookElement : bookElements) {
                //获取属性
                String id = bookElement.attributeValue("id");
                //获取子元素文本
                String title = bookElement.elementText("title");
                String author = bookElement.elementText("author");
                String price = bookElement.elementText("price");
                System.out.println("Book ID: " + id + ", Title: " + title + ", Author: " + author + ", Price: " + price);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

}
